local mywifi = require "mywifi"


--wifi连接，并设定自动重连时间
mywifi.wifiInit(4, 5, 1000)    --选择gpio4,定时器5,自动重连时间1S
--mywifi.wifiConnect(MY_SSID, MY_PASSWORD, 1000)

--成功连接并获取IP后执行mqtt
wifi.sta.eventMonReg(wifi.STA_GOTIP, function()
    mywifi.blinking()
    print("Config done, IP is "..wifi.sta.getip()) 
end)

local function updconfig()
    udpSocket = net.createUDPSocket()
    print(udpSocket)
    udpSocket:listen(5000)
    udpSocket:on("receive", function(s, data, port, ip)
        --print(string.format("received '%s' from %s:%d", data, ip, port))
        --s:send(port, ip, "echo: " .. data)
        if (string.find(data,"#") ~= nil) then 
            --str = "WIFIT440/88888888"
            str = data
            print(str)
            len = string.len(str)
            m,_ = string.find(str, "#")
            
            SSID = string.sub(str,1,m-1)
            PWR = string.sub(str,m+1,len)
    
            print(SSID, PWR)
            mywifi.wifiConnect(SSID, PWR, 1000)
        end     
    end)
    port, ip = udpSocket:getaddr()
    print(string.format("local UDP socket address / port: %s:%d", ip, port))
end

tmr.alarm(1, 5000, tmr.ALARM_AUTO, function()
            --collectgarbage("collect")
            --print("mem")
            --print(collectgarbage("count"))
            if(wifi.sta.getip() == nil) then
                wifi.ap.config({ ssid = 'mymcu', auth = AUTH_OPEN })
                wifi.setmode(wifi.SOFTAP)                   
                updconfig()
                --tmr.stop(1)
                mywifi.blinking(gpio.HIGH)
            end 
            --collectgarbage("collect")
            --print(collectgarbage("count"))
end)
        


-- ns = net.createServer(net.TCP, 15)
-- ns:listen(80, function(conn)
    -- conn:on("receive", function(sck, data)
        -- --print(d)
        -- --c:send(d)
        -- if (string.find(data,"#") ~= nil) then 
                -- --str = "WIFIT440/88888888"
                -- str = data
                -- print(str)
                -- len = string.len(str)
                -- m,_ = string.find(str, "#")
                
                -- SSID = string.sub(str,1,m-1)
                -- PWR = string.sub(str,m+1,len)
        
                -- print(SSID, PWR)
                -- wifi.setmode(wifi.STATION)
                -- wifi.sta.config(SSID, PWR)
                -- --wifiConnect(SSID, PWR, 1000)
        -- end
    -- end)
    -- conn:on("connection", function(c, d) print(d) end)
    -- conn:on("disconnection", function(c, d) print("disconnection") end)
-- end)





